package com.rm.qjson;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 前端直接提交sql到后台，查询数据，并返回json数据。
 * 
 * @author xdan
 */
public class QJsonController extends Controller {
	Logger log = Logger.getLogger(getClass());

	/**
	 * 查询
	 */
	public void query() {
		JsonData obj = new JsonData();
		try {
			String sql = getPara("sql");
			int pageNumber = getParaToInt("page");
			int pageSize = getParaToInt("rows");

			int fromIndex = sql.indexOf(" from ", 1);
			String sqlSelectPart = sql.substring(0, fromIndex);
			String sqlFromPart = sql.substring(fromIndex, sql.length());

			// 分页查询
			Page<Record> page = Db.paginate(pageNumber, pageSize,
					sqlSelectPart, sqlFromPart);
			obj.setObj(page);
		} catch (Exception e) {
			log.error("查询json数据失败！", e);
			obj.setSuccess(false);
			obj.setErrorMsg(e.getMessage());
		}
		renderJson(obj);
	}
}
